package com.wxg.ch09.leetcode303;

public class NumArrayV2 {

    /**
     * sum[i] 存储前 i 个元素的和，
     * sum[0] = 0
     * sum[i] 存储 [0...i-1] 的和
     */
    private int[] sum;

    public NumArrayV2(int[] nums) {
        sum = new int[nums.length + 1];
        sum[0] = 0;
        for (int i = 1; i < sum.length; i++) {
            sum[i] = sum[i - 1] + nums[i -1];
        }
    }

    public int sumRange(int i, int j) {
        // sum[j + 1] : 存储的是 [0...j]   的元素和
        // sum[i]     : 存储的是 [0...i-1] 的元素和
        return sum[j + 1] - sum[i];
    }
}
